import charttheme from '../assets/charttheme.json';
import * as Chart from 'echarts';

class ChartClass {
  // 静态属性存储已注册的主题
  static registeredThemes = new Set();
  static defaultOption = {
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        containlabel: true
      },
      // 完善的初始动画配置
      animation: true,                    // 开启动画
      animationDuration: 1000,
      animationEasing: 'cubicOut',
    };
  // 静态方法注册主题
  static registerTheme(themeName = 'infographic', themeConfig = charttheme) {
    if (!this.registeredThemes.has(themeName)) {
      Chart.registerTheme(themeName, themeConfig);
      this.registeredThemes.add(themeName);
    }
  }

  constructor(dom, theme = 'infographic', initOptions = {}) {
    this.chart = Chart.init(dom, theme, initOptions);
    this.dom = dom;
    this.observer = null;
    this.resizeObserver = null;


    // this.chart.setOption(this.defaultChartOptions)
    // 初始化 DOM 监听（用于销毁时清理）
    this._initObserver();
    // 初始化尺寸监听
    this._initResizeObserver();
  }

  setOption(options) {
    // 合并默认配置和传入的配置
    const mergedOptions = Object.assign({}, this.defaultchartoptions, options);
    this.chart.setOption(mergedOptions, true);
  }

  dispose() {
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }

    if (this.observer) {
      this.observer.disconnect();
      this.observer = null;
    }

    if (this.resizeObserver) {
      this.resizeObserver.disconnect();
      this.resizeObserver = null;
    }
  }
  dispatchAction(){
    this.chart.dispatchAction(...arguments);
  }
  _initObserver() {
    const parent = this.dom.parentNode;

    if (!parent) {
      this.dispose();
      return;
    }

    const observer = new MutationObserver((mutations) => {
      for (const mutation of mutations) {
        if (mutation.type === 'childList') {
          // 检查被移除的节点中是否包含当前图表DOM
          for (const removedNode of mutation.removedNodes) {
            if (removedNode.contains(this.dom) || removedNode === this.dom) {
              this.dispose();
              observer.disconnect();
              return;
            }
          }
          
          // 同时检查DOM是否仍在文档中
          if (!document.body.contains(this.dom)) {
            this.dispose();
            observer.disconnect();
            return;
          }
        }
      }
    });

    // 修改观察选项，增加subtree以监听所有子节点变化
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });

    this.observer = observer;
  }

  _initResizeObserver() {
    // const resizeObserver = new ResizeObserver(() => {
    //   if (this.chart && !this.chart.isDisposed()) {
    //     this.chart.resize();
    //   }
    // });

    // resizeObserver.observe(this.dom);

    // this.resizeObserver = resizeObserver;

    window.addEventListener('resize', () => {
      if (this.chart && !this.chart.isDisposed()) {
        console.log("窗口尺寸变化");

        
        this.chart.resize();
      }
    });

  }
}

// 静态方法调用：类初始化时注册主题
// ChartClass.registerTheme();

export default ChartClass;
